<template>
  <div class="education-page">
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="教育背景" name="education">
        <div v-if="activeTab === 'education'" class="tab-header">
          <el-button type="primary" :icon="Plus" @click="handleAddEducation">
            添加记录
          </el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="12" v-for="(edu, index) in educationList" :key="edu.id" :class="index >= 2 ? 'second-row-card' : ''">
            <el-card shadow="hover" class="education-card">
              <template #header>
                <div class="card-header">
                  <span>{{ edu.degree }}</span>
                  <span class="period">{{ edu.period }}</span>
                </div>
              </template>
              
              <div class="education-content">
                <div class="school-info">
                  <h3>{{ edu.school }}</h3>
                  <p class="major">{{ edu.major }}</p>
                  <p class="gpa">GPA: {{ edu.gpa }}</p>
                </div>
                
                <div class="education-actions">
                  <el-button size="small" :icon="View" @click="handleViewEducation(edu)">查看</el-button>
                  <el-button size="small" :icon="Edit" @click="handleEditEducation(edu)">编辑</el-button>
                  <el-button size="small" :icon="Delete" type="danger" @click="handleDeleteEducation(edu)">删除</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      
      <el-tab-pane label="专业认证" name="certifications">
        <div v-if="activeTab === 'certifications'" class="tab-header">
          <el-button type="primary" :icon="Plus" @click="handleAddCertification">
            添加认证
          </el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="8" v-for="cert in certifications" :key="cert.id">
            <el-card shadow="hover" class="cert-card">
              <div class="cert-icon">
                <el-icon :size="40" :color="cert.color">
                  <component :is="cert.icon" />
                </el-icon>
              </div>
              
              <div class="cert-info">
                <h4>{{ cert.name }}</h4>
                <p class="issuer">{{ cert.issuer }}</p>
                <p class="date">{{ cert.date }}</p>
              </div>
              
              <div class="cert-actions">
                <el-button size="small" :icon="View">查看</el-button>
                <el-button size="small" :icon="Edit">编辑</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <!-- 教育背景表单弹窗 -->
    <el-dialog v-model="educationFormVisible" :title="educationFormMode === 'add' ? '添加教育背景' : '编辑教育背景'" width="800px"
      @close="resetEducationForm">
      <div class="education-form-content">
        <el-form ref="educationFormRef" :model="educationForm" :rules="educationFormRules" label-width="120px"
          status-icon>

          <el-form-item label="学校名称" prop="school">
            <el-input v-model="educationForm.school" placeholder="请输入学校名称" maxlength="100" show-word-limit />
          </el-form-item>

          <el-form-item label="专业名称" prop="major">
            <el-input v-model="educationForm.major" placeholder="请输入专业名称" maxlength="100" show-word-limit />
          </el-form-item>

          <el-form-item label="学位" prop="degree">
            <el-input v-model="educationForm.degree" placeholder="请输入学位" maxlength="100" show-word-limit />
          </el-form-item>

          <el-form-item label="学历层次" prop="level">
            <el-select v-model="educationForm.level" placeholder="请选择学历层次" style="width: 100%">
              <el-option label="高中" value="高中" />
              <el-option label="专科" value="专科" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startDate">
                <el-date-picker v-model="educationForm.startDate" type="date" placeholder="选择开始时间"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endDate">
                <el-date-picker v-model="educationForm.endDate" type="date" placeholder="选择结束时间（留空表示至今）"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="毕业状态" prop="isGraduated">
            <el-select v-model="educationForm.isGraduated" placeholder="请选择毕业状态" style="width: 100%">
              <el-option label="已毕业" :value="1" />
              <el-option label="在读" :value="0" />
            </el-select>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="绩点" prop="gpa">
                <el-input v-model="educationForm.gpa" placeholder="如：3.8" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最高绩点" prop="maxGpa">
                <el-input v-model="educationForm.maxGpa" placeholder="如：4.0" maxlength="20" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="成就荣誉" prop="honors">
            <el-input v-model="educationForm.honors" type="textarea" :rows="3" placeholder="请输入成就荣誉，多项用换行分隔" maxlength="500" show-word-limit />
          </el-form-item>

          <el-form-item label="学习内容" prop="courseContent">
            <el-input v-model="educationForm.courseContent" type="textarea" :rows="4" placeholder="请描述主要学习内容" maxlength="1000" show-word-limit />
          </el-form-item>

        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="educationFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEducationForm">
            {{ educationFormMode === 'add' ? '添加' : '更新' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 教育背景详情查看弹窗 -->
    <el-dialog v-model="educationDetailVisible" title="教育背景详情" width="900px" :close-on-click-modal="false">
      <div class="education-detail-content" v-if="selectedEducation">
        <!-- 教育背景标题区域 -->
        <div class="education-header">
          <div class="education-title">
            <h2>{{ selectedEducation.school }}</h2>
            <div class="education-tags">
              <el-tag size="large" effect="plain">
                {{ selectedEducation.degree }}
              </el-tag>
              <el-tag size="large" effect="plain">
                {{ selectedEducation.major }}
              </el-tag>
              <el-tag size="large" :type="selectedEducation.isGraduated === 1 ? 'success' : 'warning'">
                {{ selectedEducation.isGraduated === 1 ? '已毕业' : '在读' }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 教育背景详细信息 -->
        <div class="info-sections">
          <el-card class="info-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon>
                  <School />
                </el-icon>
                <span>基本信息</span>
              </div>
            </template>

            <div class="info-grid">
              <div class="info-item">
                <label>学校名称</label>
                <div class="info-value">{{ selectedEducation.school }}</div>
              </div>

              <div class="info-item">
                <label>专业名称</label>
                <div class="info-value">{{ selectedEducation.major }}</div>
              </div>

              <div class="info-item">
                <label>学位</label>
                <div class="info-value">{{ selectedEducation.degree }}</div>
              </div>

              <div class="info-item">
                <label>学历层次</label>
                <div class="info-value">{{ selectedEducation.level }}</div>
              </div>

              <div class="info-item">
                <label>学习期间</label>
                <div class="info-value">
                  {{ formatPeriod(selectedEducation.startDate, selectedEducation.endDate) }}
                </div>
              </div>

              <div class="info-item">
                <label>毕业状态</label>
                <div class="info-value">
                  <el-tag :type="selectedEducation.isGraduated === 1 ? 'success' : 'warning'" size="small">
                    {{ selectedEducation.isGraduated === 1 ? '已毕业' : '在读' }}
                  </el-tag>
                </div>
              </div>

              <div class="info-item" v-if="selectedEducation.gpa">
                <label>绩点</label>
                <div class="info-value">{{ selectedEducation.gpa }}{{ selectedEducation.maxGpa ? '/' + selectedEducation.maxGpa : '' }}</div>
              </div>
            </div>
          </el-card>

          <el-card class="info-card" shadow="hover" v-if="selectedEducation.honors">
            <template #header>
              <div class="card-header">
                <el-icon>
                  <Trophy />
                </el-icon>
                <span>成就荣誉</span>
              </div>
            </template>

            <div class="honors-content">
              <div class="honor-item" v-for="(honor, index) in formatAchievements(selectedEducation.honors)" :key="index">
                <div class="honor-text">{{ honor }}</div>
              </div>
            </div>
          </el-card>

          <el-card class="info-card" shadow="hover" v-if="selectedEducation.courseContent">
            <template #header>
              <div class="card-header">
                <el-icon>
                  <Document />
                </el-icon>
                <span>学习内容</span>
              </div>
            </template>

            <div class="course-content">
              <p>{{ selectedEducation.courseContent }}</p>
            </div>
          </el-card>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="educationDetailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete, View, School, Trophy, Medal, Document } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { educationApi } from '@/utils/api/education'

// 响应式数据
const loading = ref(false)
const activeTab = ref('education')
const educationList = ref([])

// 专业认证测试数据
const certifications = ref([
  {
    id: 1,
    name: 'AWS Solutions Architect',
    issuer: 'Amazon Web Services',
    date: '2023-08-15',
    icon: 'Cloud',
    color: '#FF9900'
  },
  {
    id: 2,
    name: 'Kubernetes Administrator',
    issuer: 'Cloud Native Computing Foundation',
    date: '2023-06-20',
    icon: 'Monitor',
    color: '#326CE5'
  },
  {
    id: 3,
    name: 'Oracle Certified Java Programmer',
    issuer: 'Oracle Corporation',
    date: '2022-12-10',
    icon: 'Cpu',
    color: '#F80000'
  },
  {
    id: 4,
    name: 'Microsoft Azure Developer',
    issuer: 'Microsoft Corporation',
    date: '2023-03-25',
    icon: 'DataBoard',
    color: '#0078D4'
  },
  {
    id: 5,
    name: 'Google Cloud Professional',
    issuer: 'Google LLC',
    date: '2023-01-30',
    icon: 'TrendCharts',
    color: '#4285F4'
  },
  {
    id: 6,
    name: 'Docker Certified Associate',
    issuer: 'Docker Inc.',
    date: '2022-09-12',
    icon: 'Box',
    color: '#2496ED'
  }
])

// 教育背景表单相关数据
const educationFormVisible = ref(false)
const educationFormMode = ref('add') // 'add' 或 'edit'
const educationFormRef = ref()
const educationForm = reactive({
  id: null,
  school: '',
  major: '',
  degree: '',
  level: '',
  startDate: '',
  endDate: '',
  isGraduated: 1,
  gpa: '',
  maxGpa: '',
  honors: '',
  courseContent: ''
})

const educationFormRules = {
  school: [
    { required: true, message: '请输入学校名称', trigger: 'blur' },
    { min: 1, max: 100, message: '学校名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请输入专业名称', trigger: 'blur' },
    { min: 1, max: 100, message: '专业名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  degree: [
    { required: true, message: '请输入学位', trigger: 'blur' },
    { min: 1, max: 100, message: '学位长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择学历层次', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  isGraduated: [
    { required: true, message: '请选择毕业状态', trigger: 'change' }
  ]
}

// 教育背景详情查看相关数据
const educationDetailVisible = ref(false)
const selectedEducation = ref(null)

// 初始化教育背景列表
const loadEducationList = async () => {
  try {
    loading.value = true
    const response = await educationApi.queryList({})
    if (response.code === 0) {
      // 转换数据格式
      educationList.value = response.data.map(edu => ({
        id: edu.id,
        degree: edu.degree,
        school: edu.school,
        major: edu.major,
        level: edu.level,
        gpa: edu.gpa && edu.maxGpa ? `${edu.gpa}/${edu.maxGpa}` : edu.gpa || '',
        startDate: edu.startDate,
        endDate: edu.endDate,
        isGraduated: edu.isGraduated,
        honors: edu.honors,
        courseContent: edu.courseContent
      }))
    } else {
      ElMessage.error(response.message || '加载教育背景列表失败')
    }
  } catch (error) {
    console.error('加载教育背景列表失败:', error)
    ElMessage.error('加载教育背景列表失败')
  } finally {
    loading.value = false
  }
}

// 工具函数
const formatPeriod = (startDate, endDate) => {
  if (!startDate) return ''
  
  const formatDate = (dateStr) => {
    if (!dateStr) return ''
    try {
      const date = new Date(dateStr)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit' 
      })
    } catch {
      return dateStr
    }
  }
  
  if (endDate) {
    return `${formatDate(startDate)} - ${formatDate(endDate)}`
  } else {
    return `${formatDate(startDate)} - 至今`
  }
}

const formatAchievements = (achievements) => {
  if (!achievements) return []
  return achievements.split('\n').filter(item => item.trim()).map(item => item.trim())
}

// 方法
const handleAddEducation = () => {
  educationFormMode.value = 'add'
  resetEducationForm()
  educationFormVisible.value = true
}

const handleViewEducation = (education) => {
  selectedEducation.value = { ...education }
  educationDetailVisible.value = true
}

const handleEditEducation = (education) => {
  educationFormMode.value = 'edit'
  // 填充表单数据
  educationForm.id = education.id
  educationForm.school = education.school
  educationForm.major = education.major
  educationForm.degree = education.degree
  educationForm.level = education.level || ''
  educationForm.startDate = education.startDate
  educationForm.endDate = education.endDate
  educationForm.isGraduated = education.isGraduated || 1
  educationForm.gpa = education.gpa?.includes('/') ? education.gpa.split('/')[0] : education.gpa || ''
  educationForm.maxGpa = education.gpa?.includes('/') ? education.gpa.split('/')[1] : education.maxGpa || ''
  educationForm.honors = education.honors || ''
  educationForm.courseContent = education.courseContent || ''
  
  educationFormVisible.value = true
}

const handleDeleteEducation = async (education) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除教育背景「${education.school} - ${education.degree}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await educationApi.delete(education.id)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadEducationList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除教育背景失败:', error)
      ElMessage.error('删除教育背景失败')
    }
  }
}

// 表单方法
const submitEducationForm = async () => {
  if (!educationFormRef.value) return

  try {
    await educationFormRef.value.validate()

    // 处理绩点数据
    const gpa = educationForm.gpa ? parseFloat(educationForm.gpa) : null
    const maxGpa = educationForm.maxGpa ? parseFloat(educationForm.maxGpa) : null

    const apiData = {
      school: educationForm.school.trim(),
      major: educationForm.major.trim(),
      degree: educationForm.degree.trim(),
      level: educationForm.level,
      startDate: educationForm.startDate,
      endDate: educationForm.isGraduated === 1 ? educationForm.endDate : null,
      isGraduated: educationForm.isGraduated,
      gpa: gpa,
      maxGpa: maxGpa,
      honors: educationForm.honors?.trim() || '',
      courseContent: educationForm.courseContent?.trim() || ''
    }

    let response
    if (educationFormMode.value === 'add') {
      response = await educationApi.create(apiData)
    } else {
      response = await educationApi.update(educationForm.id, apiData)
    }

    if (response.code === 0) {
      ElMessage.success(educationFormMode.value === 'add' ? '添加教育背景成功' : '更新教育背景成功')
      educationFormVisible.value = false
      loadEducationList()
    } else {
      ElMessage.error(response.message || (educationFormMode.value === 'add' ? '添加教育背景失败' : '更新教育背景失败'))
    }
  } catch (error) {
    console.error('提交教育背景表单失败:', error)
    if (error !== false) { // 验证失败时不显示错误
      ElMessage.error(educationFormMode.value === 'add' ? '添加教育背景失败' : '更新教育背景失败')
    }
  }
}

const resetEducationForm = () => {
  if (educationFormRef.value) {
    educationFormRef.value.resetFields()
  }

  educationForm.id = null
  educationForm.school = ''
  educationForm.major = ''
  educationForm.degree = ''
  educationForm.level = ''
  educationForm.startDate = ''
  educationForm.endDate = ''
  educationForm.isGraduated = 1
  educationForm.gpa = ''
  educationForm.maxGpa = ''
  educationForm.honors = ''
  educationForm.courseContent = ''
}

const handleTabChange = (tab) => {
  console.log('切换到标签页:', tab)
}

const handleAddCertification = () => {
  ElMessage.info('添加专业认证功能开发中...')
}

// 生命周期钩子
onMounted(() => {
  loadEducationList()
})
</script>

<style scoped>
.education-page {
  padding: 0;
}

.tab-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.education-card,
.cert-card {
  transition: transform 0.3s;
}

/* 为教育背景第二行及以后的卡片添加上间距 */
.second-row-card {
  margin-top: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .period {
  font-size: 14px;
  color: #909399;
}

.education-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
}

.school-info h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.school-info .major {
  color: #409eff;
  margin-bottom: 4px;
}

.school-info .gpa {
  color: #606266;
  font-size: 14px;
}

.education-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-end;
  justify-content: flex-start;
  margin-left: 16px;
}

.education-actions .el-button {
  width: 85px;
  display: flex;
  justify-content: center;
  text-align: center;
}

.cert-card {
  text-align: center;
}

.cert-icon {
  margin-bottom: 16px;
}

.cert-info h4 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.cert-info .issuer {
  color: #606266;
  margin-bottom: 4px;
}

.cert-info .date {
  color: #909399;
  font-size: 14px;
  margin-bottom: 16px;
}

.cert-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
  width: 100%;
}

.cert-actions .el-button {
  width: 70px;
  display: flex;
  justify-content: center;
  text-align: center;
}

/* 表单弹窗样式 */
.education-form-content {
  max-height: calc(80vh - 180px);
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 4px;
}

/* 详情弹窗样式 */
.education-detail-content {
  padding: 0;
  max-height: calc(90vh - 240px);
  overflow-y: auto;
  overflow-x: hidden;
}

.education-title h2 {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.education-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.info-sections {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.info-card .el-card__body {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.card-header .el-icon {
  color: #409EFF;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.info-value {
  font-size: 16px;
  color: #303133;
}

.honors-content,
.course-content {
  color: #303133;
  line-height: 1.6;
  font-size: 14px;
}

.honor-item {
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.honor-item:hover {
  background: #f0f9ff;
  border-left-color: #67c23a;
}

.honor-text,
.course-content p {
  color: #303133;
  line-height: 1.6;
  font-size: 14px;
  margin: 0;
  white-space: pre-wrap;
}

.course-content p {
  white-space: pre-wrap;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-dialog {
  border-radius: 8px;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .education-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .education-actions .el-button {
    width: 75px;
  }

  .cert-actions .el-button {
    width: 60px;
  }

  .tab-header {
    justify-content: center;
  }

  .second-row-card {
    margin-top: 20px;
  }
}
</style>